<template>
  <div class="app-container">
    <!-- 添加导航栏 -->
    <div class="nav">
      <router-link to="/dashboard/dash"><span>首页</span></router-link>
      <router-link :to="{
        name: 'project-manage',
        params: {
          param: staId,
          standardName: standardName
        }
      }">
        <span>/</span><span>{{ standardName }}</span>
      </router-link>
      <router-link :to="{
        name: 'project-manage',
        params: {
          param: staId,
          standardName: standardName,
          staName: standardName
        }
      }">
        <span>/</span><span>{{ projectName }}</span>
      </router-link>
      <router-link :to="{
        name: 'moudle_select',
        params: {
          param: projectId,
          projectName: projectName,
          standardName: standardName,
          staId: staId
        }
      }">
        <span>/</span><span>模块选择</span>
      </router-link>
      <span>/</span><span>规程管理</span>
      <div class="nav-back">
        <el-button type="text" @click="handleBack">
          <i class="el-icon-arrow-left"></i> 返回
        </el-button>
      </div>
    </div>

    <div class="top-container">
      <div class="scheme-display">
        <div class="scheme-title">比对方案</div>
        <div class="scheme-content">
          <template v-if="currentPlan">
            <div class="current-plan">
              <el-tooltip :content="currentPlan.fileName" placement="top">
                <a :href="currentPlan.fileUrl" target="_blank" class="plan-name">
                  {{ currentPlan.fileName }}
                </a>
              </el-tooltip>
              <el-button
                type="text"
                class="delete-btn"
                @click="handleDeletePlan"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </template>
          <span v-else class="no-plan">暂无比对方案</span>
          
          <el-upload
            class="plan-upload"
            :action="uploadUrl"
            :headers="{
              'Authorization': 'Bearer ' + this.$store.state.user.token
            }"
            :show-file-list="false"
            :on-success="handlePlanUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforePlanUpload"
            accept=".pdf"
            name="file"
          >
            <el-button type="primary">
              {{ currentPlan ? '更换比对方案' : '上传比对方案' }}
            </el-button>
          </el-upload>
        </div>
      </div>
    </div>

    <div class="table-container">
      <!-- 将原筛选表单中的按钮和搜索框移到这里 -->
      <div class="table-header">
        <div class="left-section">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入文档标题/文件名称"
            class="search-input"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <div class="date-filter">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              class="date-picker"
              @change="handleSearch"
            />
            <el-button 
              type="primary" 
              link 
              @click="resetDateRange"
              v-if="dateRange && dateRange.length"
            >
              重置时间
            </el-button>
          </div>
        </div>

        <el-button type="primary" @click="handleAdd">
          添加操作规程
        </el-button>
      </div>

      <!-- 表格内容保持不变 -->
      <el-table
        :data="filteredTableData.slice(
          (currentPage - 1) * pageSize,
          currentPage * pageSize
        )"
        style="width: 100%"
        highlight-current-row
        border
      >
        <el-table-column prop="pgId" label="序号" width="80" />
        <el-table-column prop="pgName" label="文档标题" />
        <el-table-column label="文件名称">
          <template slot-scope="scope">
            <span class="clickable-cell" @click="openFile(scope.row)">
              {{ getFileName(scope.row.pgUrl) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button 
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTableData.length"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 添加编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="fileForm"
        :model="fileForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="文档标题" prop="title">
          <el-input v-model="fileForm.title" placeholder="请输入文档标题" />
        </el-form-item>
        <el-form-item label="文档文件">
          <el-upload
            class="upload-demo"
            :action="uploadUrl1"
            :headers="headers"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传 DOC/DOCX/PDF 文件,且不超过20MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: "",
      tableData: [],
      dialogVisible: false,
      dialogTitle: "添加文档",
      fileForm: {
        title: "",
        file: null,
      },
      fileList: [],
      rules: {
        title: [{ required: true, message: "请输入文档标题", trigger: "blur" }],
      },
      uploadUrl1:  "http://localhost:8081/program/add",
      headers: {
        Authorization: "Bearer " + this.$store.state.user.token,
      },
      isEdit: false,
      currentId: null,
      currentPage: 1,
      pageSize: 10,
      filterForm: {
        operationFilter: {
          title: "",
          fileName: "",
          dateRange: [],
        },
      },
      projectId: '',
      staId: '',
      standardName: '',
      projectName: '',
      currentPlan: null,
      uploadUrl:  'http://localhost:8081/comparison/uploadPDF',
      dateRange: [],
    };
  },
  computed: {
    filteredTableData() {
      let result = this.tableData;

      // 关键字搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(item => 
          (item.pgName?.toString().toLowerCase() || '').includes(keyword) || 
          (item.pjId?.toString().toLowerCase() || '').includes(keyword)
        );
      }

      // 日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]);
        const endDate = new Date(this.dateRange[1]);
        endDate.setHours(23, 59, 59); // 设置结束时间为当天最后一秒

        result = result.filter(item => {
          const updateTime = new Date(item.updateTime);
          return updateTime >= startDate && updateTime <= endDate;
        });
      }

      return result;
    }
  },
  created() {
    // 优先使用路由参数，如果没有则使用localStorage中存储的值
    const { param, projectName, standardName, staId } = this.$route.params;
    
    this.projectId = param || localStorage.getItem('projectId');
    this.projectName = projectName || localStorage.getItem('projectName') || '未知项目';
    this.standardName = standardName || localStorage.getItem('standardName') || '未标准';
    this.staId = staId || localStorage.getItem('staId');
    
    // 存储当前值到localStorage
    if (param) localStorage.setItem('projectId', param);
    if (projectName) localStorage.setItem('projectName', projectName);
    if (standardName) localStorage.setItem('standardName', standardName);
    if (staId) localStorage.setItem('staId', staId);

    // 获取规程列表
    this.fetchOperationProcedures();
    this.fetchCurrentPlan()
  },
  methods: {
    fetchOperationProcedures() {
      console.log('Fetching programs with projectId:', this.projectId);
      this.$http
        .get('/program/list', {
          params: {
            pjId: this.projectId
          }
        })
        .then((response) => {
          if (response.data.code === 200) {
            this.tableData = response.data.data;
          } else {
            this.$message.error(response.data.message || "获取数据失败");
          }
        })
        .catch((error) => {
          console.error("获取操作规程数据失败:", error);
          this.$message.error("获取操作规程数据失败：" + error.message);
        });
    },

    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = "添加文档";
      this.$set(this.fileForm, 'title', '');
      this.$set(this.fileForm, 'file', null);
      this.fileList = [];
      this.dialogVisible = true;
    },

    handleEdit(row) {
      this.isEdit = true;
      this.currentId = row.pgId;
      this.dialogTitle = "修改文档";
      this.$set(this.fileForm, 'title', row.pgName);
      this.$set(this.fileForm, 'file', row.pgUrl);
      this.fileList = [];
      if (row.pgUrl) {
        this.fileList = [{
          name: this.getFileName(row.pgUrl),
          url: row.pgUrl
        }];
      }
      this.dialogVisible = true;
    },

    handleDelete(row) {
      this.$confirm("确认删除该操作规程吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http
            .delete(`/program/delete/${row.pgId}`)
            .then(() => {
              this.$message.success("删除成功");
              this.fetchOperationProcedures();
            })
            .catch((error) => {
              this.$message.error("删除失败：" + error.message);
            });
        })
        .catch(() => {});
    },

    handleUploadSuccess(response) {
      console.log("这是response"+response.code)
      if (response.code === 200) {
        console.log('Upload success responseddddd:', response);
        this.fileForm.file = response.data.url;
        this.fileList = [{
          name: this.getFileName(response.data.url),
          url: response.data.url
        }];
        this.$set(this.fileForm, 'file', response.data.url);
        this.$message.success("文件上传成功");
      } else {
        this.$message.error(response.message || "文件上传失败");
      }
    },

    handleUploadError(error) {
      this.$message.error("文件上传失败：" + error.message);
    },

    beforeUpload(file) {
      const isValidType = [
        "application/pdf",
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      ].includes(file.type);

      if (!isValidType) {
        this.$message.error("只能上传 DOC/DOCX/PDF 格式的文件!");
        return false;
      }

      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error("文件大小不能超过20MB!");
        return false;
      }
      return true;
    },

    submitForm() {
      this.$refs.fileForm.validate((valid) => {
        if (valid) {
          console.log('Form data before submit:', this.fileForm);
          // 检查是否已上传文件
          if (!this.fileForm.file) {
            console.log('No file uploaded');
            this.$message.error('请先上传文件');
            return;
          }

          const formData = {
            pgName: this.fileForm.title,
            pgUrl: this.fileForm.file,
            pgType: "1",
            pjId: this.projectId,
            updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
          };

          console.log('Submitting form data:', formData);

          const api = this.isEdit
            ? this.$http.put(`/program/update/pgId/${this.currentId}`, formData)
            : this.$http.post("/program/add1", formData);

          api.then((response) => {
            console.log('Submit response:', response);
            if (response.data.code === 200) {
              this.$message.success(this.isEdit ? "修改成功" : "添加成功");
              this.dialogVisible = false;
              this.fetchOperationProcedures();
            } else {
              this.$message.error(response.data.message || "操作失败");
            }
          }).catch((error) => {
            console.error('操作失败:', error);
            this.$message.error("操作失败：" + error.message);
          });
        }
      });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },

    handleCurrentChange(val) {
      this.currentPage = val;
    },

    handleFilter() {
      this.currentPage = 1;
    },

    resetFilter() {
      this.filterForm.operationFilter = {
        title: "",
        fileName: "",
        dateRange: [],
      };
      this.handleFilter();
    },

    handleBack() {
      this.$router.push({
        name: 'moudle_select',
        params: {
          param: this.projectId,
          projectName: this.projectName,
          standardName: this.standardName,
          staId: this.staId
        },
        replace: true
      });
    },

    // 获取当前比对方案
    async fetchCurrentPlan() {
      try {
        console.log('Fetching current plan for projectId:', this.projectId);
        const response = await this.$http.get('/comparison/current-plan',{
         params: {
            pjId: this.projectId
          }
        })
        if (response.data && (response.data.data || response.data)) {
          this.currentPlan = response.data.data || response.data
        }
      } catch (error) {
        console.error('获取比对方案失败:', error)
      }
    },

    // 上传前验证
    beforePlanUpload(file) {
      const isPdf = file.type === 'application/pdf'
      if (!isPdf) {
        this.$message.error('只能上传 PDF 文件!')
        return false
      }
      
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过20MB!')
        return false
      }

      // 如果已有方案，提示认更换
      if (this.currentPlan) {
        return new Promise((resolve, reject) => {
          this.$confirm('已存在比对方案，是否确认更换？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            resolve(true)
          }).catch(() => {
            reject(new Error('取消上传'))
          })
        })
      }
      
      return true
    },

    // 上传成功处理
    handlePlanUploadSuccess(response, file) {
      // 检查响应格式并提取数据
      const responseData = response.data || response;
      
      this.currentPlan = {
        fileName: file.name,  // 使用文件原始名称
        fileUrl: responseData.fileUrl || responseData,  // 适应不同的响应格式
        file: file.raw  // 保存文件对象以供后续使用
      }
      
      this.$message.success(this.currentPlan ? '方案更新成功' : '方案上传成功')
      
      // 更新后端记录
      console.log("视频上传失败:this.currentPlan");
      this.updatePlanRecord(file.name);
      
    },

    // 更新方案记录
    updatePlanRecord(planInfo) {
       
      let  formData = new FormData();
      formData.append("originalFilename", planInfo);
      formData.append("projectId", this.projectId);
    //  console.log("asdasdasda:"+formData.get(projectId));
      this.$http.post("/comparison/uploadPDF1",  formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then((response) => {
          //alert("视频上传成功");
        })
        .catch((error) => {
         // console.error("视频上传失败:this.projectId", this.projectId, error);
          //alert("视频上传失败，请重试");
        });
        
        
      
    },

    // 删除方案
    handleDeletePlan() {
      this.$confirm('确认删除当前比对方案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$http.delete('/comparison/delete-plan')
          this.currentPlan = null
          this.$message.success('删除成功')
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },

    // 上传错误处理
    handleUploadError(error) {
      console.error('上传失败:', error)
      this.$message.error('文件上传失败，请重试3232:${this.$route.params.param}',this.$route.params.param)
    },

    // 添加新的打开文件方法
    openFile(row) {
      console.log('Opening file:', row);
      if (row.pgUrl) {
        const fileUrl = process.env.VUE_APP_BASE_API + row.pgUrl;
        window.open(fileUrl, "_blank");
      } else {
        this.$message.warning('文件不存在');
      }
    },

    handleSearch() {
      this.currentPage = 1; // 重置到第一页
    },

    resetDateRange() {
      this.dateRange = []; // 清空日期范围
      this.handleSearch(); // 触发搜索更新
    },

    getFileName(url) {
      if (!url) return '无文件';
      return url.split('/').pop() || '未知文件';
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.top-container {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;

  .scheme-display {
    .scheme-title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      margin-bottom: 16px;
      position: relative;
      padding-left: 12px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background-color: #409EFF;
        border-radius: 2px;
      }
    }

    .scheme-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 24px;
      background-color: #f8f9fa;
      border-radius: 4px;

      .current-plan {
        display: flex;
        align-items: center;
        gap: 12px;
        max-width: 70%;

        .plan-name {
          color: #409EFF;
          font-size: 14px;
          text-decoration: none;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          
          &:hover {
            color: #66b1ff;
            text-decoration: underline;
          }
        }

        .delete-btn {
          padding: 4px;
          color: #909399;
          
          &:hover {
            color: #F56C6C;
          }
        }
      }

      .no-plan {
        color: #909399;
        font-size: 14px;
      }

      .plan-upload {
        .el-button {
          padding: 8px 16px;
        }
      }
    }
  }
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toggle-group {
  display: none;
}

.filter-form {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.filter-form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-form-inline .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
  vertical-align: top;
}

.filter-form-inline .el-input {
  width: 200px;
}

.filter-form-inline .el-date-editor {
  width: 320px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 20px;
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
}

.el-table .el-button {
  padding: 0 8px;
}

.filter-item .el-input__inner {
  border-radius: 20px;
}

.el-dialog .el-form-item {
  margin-bottom: 20px;
}

.el-dialog .el-date-editor {
  width: 100%;
}

.el-dialog .dialog-footer {
  text-align: right;
}

.upload-demo {
  width: 100%;
}

.el-upload__tip {
  line-height: 1.2;
  margin-top: 5px;
  color: #909399;
}

.operation-buttons {
  margin-left: 10px;
  white-space: nowrap;
}

.operation-buttons .el-button {
  margin-left: 5px;
}

.operation-buttons .el-button:first-child {
  margin-left: 0;
}

@media screen and (max-width: 768px) {
  .operation-buttons {
    margin-left: 0;
    display: flex;
    justify-content: flex-end;
    width: 100%;
  }

  .operation-buttons .el-button {
    flex: 1;
  }
}

.nav {
  position: relative;
  background-color: #f0f0f0;
  padding: 10px 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.nav a {
  color: #409EFF;
  text-decoration: none;
}

.nav a:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.nav span {
  color: #606266;
}

.nav-back {
  position: absolute;
  right: 20px;
}

.nav-back .el-button {
  font-size: 14px;
  padding: 0;
}

.nav-back .el-button i {
  margin-right: 4px;
}
</style>

<style lang="scss" scoped>
.search-and-plan {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  
  .plan-display {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .plan-label {
      color: #606266;
      font-size: 14px;
    }
    
    .plan-name {
      color: #409EFF;
      font-size: 14px;
      max-width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-decoration: none;
      
      &:hover {
        text-decoration: underline;
      }
    }
    
    .no-plan {
      color: #909399;
      font-size: 14px;
    }
    
    .delete-btn {
      padding: 0;
      font-size: 14px;
      color: #F56C6C;
      
      &:hover {
        color: #f78989;
      }
    }
    
    .plan-upload {
      margin-left: 15px;
    }
  }
}

.clickable-cell {
  color: #409EFF;
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}

.table-container {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .left-section {
      display: flex;
      gap: 16px;
      align-items: center;

      .search-input {
        width: 240px;
      }

      .date-filter {
        display: flex;
        align-items: center;
        gap: 8px;

        .el-button {
          height: 32px;
          margin-left: 8px;
        }
      }
    }
  }
}
</style>
